package com.juzipi.thread.test.procum;

/**
 * @Author juzipi
 * @Date 2021/6/17 16:27
 * @Info
 */
public class Demo1 {
    //信号灯法，标志位解决
    public static void main(String[] args) {
        Tv tv = new Tv();
        new Actor(tv).start();
        new Audience(tv).start();

    }

}

//生产者,演员
class Actor extends Thread{
    Tv tv;

    public Actor(Tv tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            if (i%2 == 0){
                this.tv.play("银河剧场");
            }else {
                this.tv.play("少儿频道");
            }
        }
    }

}

//消费者，观众
class Audience extends Thread{
    Tv tv;

    public Audience(Tv tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            tv.watch();
        }
    }

}

class Tv{

    //演员表演，观众等待
    //观众观看，演员等待
    String program;//节目

    boolean flag = true;

    //表演
    public synchronized void play(String program){
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了 ________>>>>>>>"+program);
        //通知观众
        this.notifyAll();
        this.program = program;
        this.flag = !this.flag;
    }


    public synchronized void watch(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了:--------->>>>>"+program);
        //通知演员来表演
        this.notifyAll();
        this.flag = !this.flag;
    }


}

